/** ************************ Global variables and classes ************ */
// var serverDomain = "http://161.53.67.206/test/";
var serverDomain = "http://localhost:8000/";
var SERVER_ACTION_CONTENT = "json/content";
var SERVER_ACTION_SEARCH = "json/search/";
var WindowAndTabInfo = {
	window_id : undefined,
	tab_id : undefined,
	tab_index : undefined,
	tab_url : undefined
};

// home variable is an id of text area or text box where the user is editing
// his/her content
var home = "";

var catch_script_active = false;

var resetting = false;
function IdClient() {
	this.id = "0";
}

var id_client = new IdClient();
var discovery;

// content and context collected from user
var currentCC = new Content("");

function Content(content, context) {
	this.id = id_client.id;
	this.content = content;
	// if(context != undefined) this.context = context;
	// else this.context = new Array();
}

var Discovery = [ {
	priority : "",
	link : [],
	group : ""
} ];

function isItFirstTime() {
	if (id_client.id == "0")
		return true;
	// if (home == "")
	// return true;
	return false;
}
function isResetting() {
	return resetting;
}
function setResetting() {
	resetting = true;
}
function setNotResetting() {
	resetting = false;
}
/** **************************************************************** */

function reset() {
	WindowAndTabInfo.window_id = undefined;
	id_client.id = "0";
	resetCatchScript();
	setResetting();
	sendCommandToHippo('first');
}
// returns to popup WindowAndTabInfo object
function getWindowAndTabInfo() {
	if (WindowAndTabInfo.window_id == undefined) {
		chrome.windows.getCurrent(function(w) {
			WindowAndTabInfo.window_id = w.id;
			chrome.tabs.getSelected(w.id, function(t) {
				WindowAndTabInfo.tab_id = t.id;
				WindowAndTabInfo.tab_index = t.index;
				WindowAndTabInfo.tab_url = t.url;
				sendCommandToHippo('info');
			});
		});
	} else
		sendCommandToHippo('info');
}

// auxiliary function to create XMLHttpRequest object
function getXMLHttpReqObject() {
	var xml_http_req = null;
	if (window.XMLHttpRequest) {
		xml_http_req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xml_http_req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xml_http_req;
}

/** *********************** Content ************************** */

function sendContent(content) {
	currentCC.content = content;
	if (isMediaWikiPage()) {
		cleanWikiContent();
	}
	var message = objectToJson(currentCC);
	sendContentRequest(message, id_client.id);
}

// within this function we use HTTP POST request to send content to server
// format of the message should be following {“id”: “user’s id”,“content”:
// “user’s content”,
// “context”: [“contextA”,”contextB”]} so everything could function format is
// provided by parameter contentMessage
// answer to this request is id of this client, which is put in global variable
// idClient

function sendContentRequest(contentMessage, id) {
	var server = serverDomain + SERVER_ACTION_CONTENT; // server's address
	var xmlHttpReq = getXMLHttpReqObject();
	xmlHttpReq.onreadystatechange = function() {
		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
				if (id != 0 && isResetting()) {
					return;
				}
				if (id == 0 && isResetting()) {
					setNotResetting();
				}
				id_client = jsonToObject(xmlHttpReq.responseText);
				currentCC.id = id_client.id;
				receiveKeywords();
				receiveReferences();
				setNotResetting();
				showContent();

			} else
				errorContent(xmlHttpReq);
		}

	};
	xmlHttpReq.open("POST", server, true);
	xmlHttpReq.setRequestHeader('Content-Type',
			'application/x-www-form-urlencoded; charset=UTF-8');
	xmlHttpReq.send(contentMessage);
}

// within this function we use HTTP POST request to get links from server
// format of the message should be following {“id”:”user’s id”}
// response received from server is [“discovery”:{“priority”: “link’s
// priority”,“keyword”:”keywordA”,“link”:”link”, “description”:”description”}]
// message gets parsed and values are stored in global variable discovery

function receiveReferences() {
	var server = serverDomain + SERVER_ACTION_SEARCH + id_client.id; // server's
	// address
	var xmlHttpReq = getXMLHttpReqObject();
	xmlHttpReq.onreadystatechange = function() {
		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
				if (!isItFirstTime()) {
					Discovery = jsonToObject(xmlHttpReq.responseText);
					showSearch();
				}
			} else
				errorSearch(xmlHttpReq);
		}

	};
	xmlHttpReq.open("GET", server, true);
	xmlHttpReq.setRequestHeader('Content-Type',
			'application/json; charset=UTF-8');
	xmlHttpReq.send();
}
/** ********************************************************************************************** */

function showSearch() {
	sendCommandToHippo("discovery");
}
function errorSearch(xmlHttpReq) {
	sendCommandToHippo("error", xmlHttpReq.status);
}
function showKeywords() {
	sendCommandToHippo("keywords");
}
function errorKeyword(xmlHttpReq) {
	sendCommandToHippo("error", xmlHttpReq.status);
}

function errorContent(xmlHttpReq) {
	sendCommandToHippo("error", xmlHttpReq.status);
}

function showContent() {
	sendCommandToHippo("content");
}

function sendCommandToHippo(command, message) {
	var viewTabUrl = chrome.extension.getURL('hippopotamus.html');
	var views = chrome.extension.getViews();
	for ( var i = 0; i < views.length; i++) {
		var view = views[i];
		// If this view has the right URL and hasn't been used yet...
		if (view.location.href == viewTabUrl) {
			// ...call one of its functions and set a property.
			switch (command) {
			case "first":
				view.setTaContent(" ");
				view.deleteOldKeywords();
				view.deleteOldLinks();
				view.setPendingStatus();
			case "content":
				view.setTaContent(currentCC.content);
				break;
			case "keywords":
				view.deleteOldKeywords();
				view.setKeywords(Keywords.sort(sortRulePriority));
				break;
			case "discovery":
				view.deleteOldLinks();
				view.setLinks(Discovery);
				break;
			case "info":
				view.setWindowAndTabInfo(WindowAndTabInfo);
				break;
			case "copy":
				view.setTextToCopy(selected_text);
				break;
			case "error":
				view.setErrorMessage(message);
				break;
			default:
				break;
			}

			break;
		}
	}
}

// function injects code from js/catch.js file in currently open tab
// and then receives collected content, from textareas and text boxes, and
// displays it in textarea in extension
function catchContent() {
	if (!isCatchScriptActive()) {
		chrome.tabs.executeScript(null, {
			file : "js/content_scripts/catch.js"
		});
		catch_script_active = true;
	}
	chrome.tabs.sendRequest(WindowAndTabInfo.tab_id, {
		action : "catch"
	}, function(response) {
		sendContent(response.content);
	});
}

// function takes care that only one script 'insert.js' is inserted a page
function isCatchScriptActive() {
	return catch_script_active;
}
function resetCatchScript() {
	catch_script_active = false;
}

// function injects a script in page which defines what is the home element
// where new content should be copied in
function defineHome() {
	resetCatchScript();
	chrome.tabs.executeScript(null, {
		file : "js/content_scripts/home.js"
	});
	chrome.tabs.sendRequest(WindowAndTabInfo.tab_id, {
		action : "home"
	}, function(response) {
		home = response.home;
	});
}

var viewing_group;
function setGroupLinks(id_group) {
	viewing_group = id_group;
}
function getGroupLinks() {

	var links;
	for (i = 0; i < Discovery.length; i++) {
		if (Discovery[i].group == viewing_group) {
			links = Discovery[i].link;
		}
	}
	return {
		win_id : WindowAndTabInfo.window_id,
		tab_index : WindowAndTabInfo.tab_index,
		discoveries : links,
		group : viewing_group
	};
}
